package com.czy.interceptor;

import com.czy.utils.JwtUtils;
import com.czy.utils.ThreadLocalUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override // 目标资源方法执行前执行， 返回 ture：放行 false 不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求头中的token
        String token = request.getHeader("authorization");

        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 移除 "Bearer " 前缀
        }

        //判断token是否存在，不存在，说明用户没有登录
        if (token == null || token.isEmpty()){
            log.info("令牌为空，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //存在，校验令牌，失败 -> 返回错误信息
        try {
            Claims claims = JwtUtils.parseToken(token);

            //拿到令牌，将用户id存入线程局部变量中
            Integer userId = Integer.parseInt(claims.get("id").toString());
            ThreadLocalUtils.setCurrentId(userId);//存入
            log.info("当前员工ID为：{}，将其存入线程局部变量中",userId);
        } catch (Exception e) {
            log.info("令牌非法，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }


        //通过校验
        log.info("令牌校验通过，放行");
        return true;
    }
}
